<?php

// error_reporting(E_ALL);
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/topthink/framework/src/helper.php';

const DS           = DIRECTORY_SEPARATOR;
const ROOT_PATH    = __DIR__ . DS . '..' . DS;
const INSTALL_PATH = ROOT_PATH .  'install' . DS;
// const CONFIG_PATH  = ROOT_PATH . 'install' . DS;

function json(array $data = [])
{
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    return;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $errorMsg = "";

    if (is_file(ROOT_PATH . 'install' . DS . 'install.lock')) {
        $errorMsg = '已安装系统，如需重新安装请删除文件：/install/install.lock';
    } elseif (!is_readable(ROOT_PATH . 'install' . DS) && !is_writable(ROOT_PATH . 'install' . DS)) {
        $errorMsg = ROOT_PATH . 'install' . DS . '：读写权限不足';
    } elseif (version_compare("8.0.0", PHP_VERSION) >= 0) {
        $errorMsg = 'PHP版本不能小于8.0.0';
    } elseif (!extension_loaded("PDO")) {
        $errorMsg = '当前未开启PDO，无法进行安装';
    }


    $post = $_POST; //post数据 

    if (strlen($post['password']) < 6) {
        $errorMsg = '管理员密码不能小于6位数';
    } elseif (strlen($post['username']) < 6) {
        $errorMsg = '管理员账号不能小于6位数';
    }

    if ($errorMsg != "") {
        return  json(["code" => 2, "msg" => $errorMsg]);
    }

    $hostname = $post["hostname"];
    $db_username = $post["db_username"];
    $db_password = $post["db_password"];
    $database = $post["database"];
    $hostport = $post["hostport"];
    $username = $post["username"];
    $password = $post["password"];

    try {
        // 先连接到MySQL服务器(不指定数据库名)
        $mysqli = new mysqli($hostname, $db_username, $db_password, '', (int)$hostport);

        // 检查连接是否成功
        if ($mysqli->connect_error) {
            return json(["code" => 0, "msg" => '数据库服务器连接失败: ' . $mysqli->connect_error]);
        }

        // 设置字符集
        $mysqli->set_charset('utf8');

        // 检查数据库是否存在
        $checkDbSql = "SHOW DATABASES LIKE '$database'";
        $result = $mysqli->query($checkDbSql);
        
        if ($result->num_rows == 0) {
            // 数据库不存在，创建数据库
            $createDbSql = "CREATE DATABASE `$database` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
            if (!$mysqli->query($createDbSql)) {
                return json(["code" => 0, "msg" => '数据库创建失败: ' . $mysqli->error]);
            }
        }
        
        // 选择/连接到目标数据库
        if (!$mysqli->select_db($database)) {
            return json(["code" => 0, "msg" => '无法选择数据库: ' . $mysqli->error]);
        }
        
        // 释放结果集
        $result->free();

        // SQL文件路径
        $sqlFile = INSTALL_PATH . 'kllxs.sql';

        // 读取SQL文件内容
        $sql = file_get_contents($sqlFile);

        // 执行SQL语句
        if (!$mysqli->multi_query($sql)) {
            return json(["code" => 0, "msg" => '数据库导入失败: ' . $mysqli->error]);
        }

        // 依次释放和丢弃所有未处理的结果集
        while ($mysqli->more_results() && $mysqli->next_result()) {
            $result = $mysqli->use_result();
            if ($result instanceof mysqli_result) {
                $result->free();
            }
        }

        // 创建install.lock文件
        $file = fopen(ROOT_PATH . 'install' . DS . 'install.lock', "w");
        if (!$file) {
            return json(["code" => 0, "msg" => ROOT_PATH . 'install' . DS . '：读写权限不足']);
        }

        $envFile = <<<EOT
APP_DEBUG = false

DB_TYPE = mysql
DB_HOST = $hostname
DB_NAME = $database
DB_USER = $db_username
DB_PASS = $db_password
DB_PORT = $hostport
DB_CHARSET = utf8
DB_PREFIX = kllxs_

DEFAULT_LANG = zh-cn
EOT;
        // 写入.env文件
        $isEnv = file_put_contents("../.env", $envFile);
        if (!$isEnv) {
            return json(["code" => 0, "msg" => '根目录权限不足']);
        }
        // 加密密码
        $newPassword = password_hash($password, PASSWORD_DEFAULT);
        // 更新管理员用户名和密码
        $updateSql = "UPDATE kllxs_admin SET username = '$username', password = '$newPassword' WHERE id = 1";
        if (!$mysqli->query($updateSql)) {
            return json(["code" => 0, "msg" => '管理员用户名和密码更新失败: ' . $mysqli->error]);
        }

        // 关闭数据库连接
        $mysqli->close();

        return json(["code" => 1, "msg" => $errorMsg, "url" => "/admin/login/log.html"]);
    } catch (Throwable $e) {
        return json(["code" => 0, "msg" => $e->getMessage()]);
    }
}



?>
<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>安装后台程序</title>
    <link rel="stylesheet" href="static/admin/layui/css/layui.css">
    <script src="static/admin/layui/layui.js"></script>
</head>
<style>
    body {
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .demo-login-container {
        width: 320px;
        margin: 21px auto 0;
    }

    .demo-login-other .layui-icon {
        position: relative;
        display: inline-block;
        margin: 0 2px;
        top: 2px;
        font-size: 26px;
    }
</style>

<body>
    <form class="layui-form layui-form-pane">
        <div class="demo-login-container">
            <h1>安装后台程序</h1>
            <div class="layui-form-item">
                <label class="layui-form-label">数据库地址</label>
                <div class="layui-input-block">
                    <input type="text" name="hostname" value="127.0.0.1" lay-verify="required" placeholder="数据库地址" lay-reqtext="请填写数据库地址" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">数据库端口</label>
                <div class="layui-input-block">
                    <input type="text" name="hostport" value="3306" lay-verify="required" placeholder="数据库端口" lay-reqtext="请填写数据库端口" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">数据库名称</label>
                <div class="layui-input-block">
                    <input type="text" name="database" value="kllxs_admin" lay-verify="required" placeholder="数据库名称" lay-reqtext="请填写数据库名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">数据库账号</label>
                <div class="layui-input-block">
                    <input type="text" name="db_username" value="root" lay-verify="required" placeholder="数据库账号" lay-reqtext="请填写数据库账号" autocomplete="off" class="layui-input" lay-affix="clear">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">数据库密码</label>
                <div class="layui-input-block">
                    <input type="password" name="db_password" value="" lay-verify="required" placeholder="数据库密码" lay-reqtext="请填写数据库密码" autocomplete="off" class="layui-input" lay-affix="eye">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">管理员账号</label>
                <div class="layui-input-block">
                    <input type="text" name="username" value="kkadmin" lay-verify="required" placeholder="管理员账号" lay-reqtext="请填写管理员账号" autocomplete="off" class="layui-input" lay-affix="clear">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">管理员密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" value="" lay-verify="required" placeholder="管理员密码" lay-reqtext="请填写管理员密码" autocomplete="off" class="layui-input" lay-affix="eye">
                </div>
            </div>
            <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login">确定安装</button>
            </div>
        </div>
    </form>
    <script>
        layui.use(["form", "layer", "jquery"], function() {
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;
            // 提交事件
            form.on('submit(demo-login)', function(data) {
                layer.load();
                var field = data.field; // 获取表单字段值
                $.post("", field, function(res) {
                    res = JSON.parse(res);
                    if (res.code == 1) {
                        layer.msg("安装成功,跳转到后台", {
                            icon: 1
                        }, function() {
                            window.location.href = res.url
                        })
                    } else {
                        layer.msg(res.msg, {
                            icon: res.code
                        }, function() {
                            layer.closeAll('loading')
                        })
                    }
                })
                return false; // 阻止默认 form 跳转
            });
        });
    </script>
</body>

</html>